/**
 * common
 * 共用JS
 */
layui.config({
    base: ctxPath+"js/util/layui-module/"
}).extend({
    treeSelect: "treeSelect",
    treeTable: "treeTable",
    iconSelected: "iconSelected/js/index",
    layMin: "layMin/layMin",
});


var layer;
var layMin;
var form;
var mobileMin = 1100; // 小于这个为移动模式

$(function () {
    layui.define(['layer', 'form', 'util', 'layMin'], function (exports) {
        "use strict";
        var util = layui.util;
        layer = layui.layer;
        form = layui.form;
        layMin = layui.layMin;

        var common = {
            // 抛出一个异常错误信息
            throwError: function (msg) {
                throw new Error(msg);
                return;
            },
            // 弹出一个错误提示
            msgError: function (msg) {
                layer.msg(msg, {
                    icon: 5
                });
                return;
            }
        };
        exports('my', common);
        // 回到顶部
        util.fixbar({
            top: true,
            css: {
                right: 15,
                bottom: 35
            },
            bgcolor: '#adaeaf',
            showHeight: 100,
            click: function (type) {
                if (type === 'top') {
                    $('.layui-body').animate({// 主要代码
                        scrollTop: 0
                    }, 200);
                }
            }
        });

        /** 表单校验-自定义*/
        form.verify({
            bt: function(value, item){
                if(!value){
                    $(item).addClass("lay-input-req");
                    layer.tips($(item).attr("lay-reqtext") || "必填", item, {
                        tips: [1, '#79c758'],// 提示方向：1上 2左 3下 4右，提示框背景颜色
                        tipsMore: false, // 开启悬浮多个提示
                        time: 3000 // 显示 3 秒
                    });
                    return true;
                }else{
                    $(item).removeClass("lay-input-req");
                    return false;
                }
            },
            bx: function(value, item){
                if(!value){
                    //$(item).addClass("lay-input-req");
                    var tipsObj = $(item).next().find("input");
                    layer.tips($(item).attr("lay-reqtext") || "必选", tipsObj, {
                        tips: [1, '#79c758'],// 提示方向：1上 2左 3下 4右，提示框背景颜色
                        tipsMore: false, // 开启悬浮多个提示
                        time: 3000 // 显示 3 秒
                    });
                    return true;
                }else{
                    //$(item).removeClass("lay-input-req");
                    return false;
                }
            }
        })
        
        // 表单必填*号 
        $(".req").append("<span style='color:red;'>*</span>");
        
        // 调用父窗口函数
        $("body").click(function(){
            var len = $(".lay-tab-title-right-close").length;
        	window.parent.commonMain(len);
        })

        // 按钮-左侧展开收起
        $(".lay-left-hiden").click(function () {
            showHidenLeft(this);
        })
        // 背景-左侧展开收起
        $(".lay-left-bg").click(function () {
            showHidenLeft(".lay-left-hiden");
        })
        // 背景-左侧树形选择加颜色
        $(".lay-left-tree").on("click", ".layui-tree-main", function () {
            $(".lay-tree-main-bg").removeClass("lay-tree-main-bg");
            $(this).addClass("lay-tree-main-bg");
        })

        // 初始化加载合适大小
        initReSize();


    });

    
})



/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 监听浏览器变化（兼容窗口）
 */
$(window).resize(function(){
    initReSize();
})

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 移动/PC直接切换
 */
function initReSize() {
    var w = $(document).width();
    var h = $(document).height();
    h = h - 120;
    $(".lay-left-box").css("height", h+"px")
    if(w < mobileMin){
        showHidenLeft(".lay-left-hiden", 1);
    }else {
        showHidenLeft(".lay-left-hiden", 2);
    }
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 左侧显示隐藏
 */
function showHidenLeft(obj, mark) {
    var layId = $(obj).attr("lay-id");
    if((layId == 1 && !mark) || mark == 2){
        $(obj).attr("lay-id", 0);
        $(obj).find("i").html("&#xe603;");
        var w = $(document).width();
        if(w < mobileMin){
            $(obj).css("left", "81.1%");
            $(".lay-left-box").css({"width": "80%", "overflow": "auto", "border": "1px solid #f3f3f3"});
            $(".lay-right-box").css({"width": "99%", "left": "1%"});
            $(".lay-left-bg").css("display", "block");
        }else {
            $(obj).css("left", "19.1%");
            $(".lay-left-box").css({"width": "18%", "overflow": "auto", "border": "1px solid #f3f3f3"});
            $(".lay-right-box").css({"width": "80%", "left": "20%"});
            $(".lay-left-bg").css("display", "none");
        }
    }else {
        $(obj).attr("lay-id", 1);
        $(obj).css("left", "0");
        $(obj).find("i").html("&#xe602;");
        $(".lay-left-box").css({"width": "0%", "overflow": "hidden", "border": "none"});
        $(".lay-right-box").css({"width": "99%", "left": "1%"});
        $(".lay-left-bg").css("display", "none");
    }
}


/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 *  (脱敏)将字符串截断成***
 * @param str 要进行隐藏的变量
 * @param frontLen 前面需要保留几位
 * @param endLen 后面需要保留几位
 * @returns
 */
function hidenNum(str, frontLen, endLen) {
    if (str && str.length > 10) {
        var len = str.length - frontLen - endLen;
        var xing = '';
        for (var i = 0; i < len; i++) {
            xing += '*';
        }
        return str.substring(0, frontLen) + xing + str.substring(str.length - endLen);
    }
    return str;
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 字符串转换***
 * @param str 要进行隐藏的变量，隐藏中间
 * @returns
 */
function hidenName(str){
    if(str && str.length > 1){
        if(str.length == 2){
            return str.substring(0, 1) + "*";
        }else{
            var xing = '';
            for(var i=1; i<str.length-1; i++){
                xing += '*';
            }
            return str.substring(0, 1) + xing + str.substring(str.length-1, str.length);
        }
    }
    return str || "";
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 过滤提交的字段数据，查看标签下的无需提交
 */
function filterField(formId, data){
    if(!data){
        return {};
    }
    var result = {};
    for(var key in data){
        var obj = $(formId).find(".lay-detail").find("[name='"+key+"']")[0];
        if(!obj){
            result[key] = data[key];
        }
    }
    return result;
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 加载错误照片
 * @param $obj
 */
function errorImg($obj, key) {
    var value = $($obj).attr("key-id");
    if((!value || value == 0) && !key){
        $($obj).attr({"src": ctxPath+"images/head.png", "onerror": "", "key-id": "1"});
    }else if (key && key == 1){
        //$($obj).attr({"src": "images/head2.png", "onerror": "", "key-id": "1"});
    }
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 表格左浮动-兼容手机模式
 * @returns
 */
function isLeft(){
    var w = $(document).width();
    if(w < mobileMin){
        return '';
    }else{
        return 'left';
    }
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 表格右浮动-兼容手机模式
 * @returns
 */
function isRight(){
	var w = $(document).width();
	if(w < mobileMin){
		return '';
	}else{
		return 'right';
	}
}


var tempDictObjct, tempDictArray;
/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 数字字典数据获取
 * @param key 对应数字字典编码
 * @param lableId 标签id
 * @param name 标签name
 * @param req 是否必填
 * @param laType 1单选框 2 复选框 3下拉框
 */
function getDictLabel(key, lableId, name, req, laType){
	if(!tempDictArray){
		tempDictArray = sessionStorage.getItem("dict_list");
		tempDictArray = tempDictArray?JSON.parse(tempDictArray):null;
		if(!tempDictArray){// 如果sessionStorage内存过小未存储，则去后台查询
            $.post(ctxPath+"sys/dict/getDictAll",{},function(res){
                if(res.success){
                    tempDictObjct = res.data['dict_map'];
                    tempDictArray = res.data['dict_list'];
                    getDictLabel(key, lableId, name, req, laType);
                }
            })
        }
	}
	var s = "";
	if(tempDictArray){
		for(var i=0; i<tempDictArray.length; i++){
			var dict = tempDictArray[i];
			if(dict.dictCode == key){
				var setupList = dict.setupList;
				if(laType){// 用于自定义标签类型
					dict.dictType = laType;
				}
				if(dict.dictType == 1){// 1单选框2复选框3下拉框
					for(var j=0; j<setupList.length; j++){
						s += '<input type="radio" name="'+name+'" value="'+setupList[j].code+'" title="'+setupList[j].remarks+'" '+(j==0?'checked':'')+'>';
					}
				}else if(dict.dictType == 2){
					for(var j=0; j<setupList.length; j++){
						s += '<input type="checkbox" name="'+name+'" value="'+setupList[j].code+'" lay-skin="primary" title="'+setupList[j].remarks+'">';
					}
				}else if(dict.dictType == 3){
					s += "<select name='"+name+"' lay-id='"+name+"' "+(req?"lay-verify='bx'":'')+">";
					s += "<option value=''></option>";
					for(var j=0; j<setupList.length; j++){
						s += "<option value='"+setupList[j].code+"'>"+setupList[j].remarks+"</option>";
					}
					s += "</select>";
				}
				break;
			}
		}
	}
	$(lableId).html(s);
	form.render();
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 数字字典数据获取
 * @param key 对应数字字典编码
 * @param code 存储值
 * @param color 默认不传参无样式，1为内容加颜色，2为加背景颜色
 * @returns
 */
function getDictText(key, code, color){
	if(!tempDictObjct){
		tempDictObjct = sessionStorage.getItem("dict_map");
		tempDictObjct = tempDictObjct?JSON.parse(tempDictObjct):null;
        if(!tempDictObjct){// 如果sessionStorage内存过小未存储，则去后台查询
            $.post(ctxPath+"sys/dict/getDictAll",{},function(res){
                if(res.success){
                    tempDictObjct = res.data['dict_map'];
                    tempDictArray = res.data['dict_list'];
                    getDictText(key, code, color);
                }
            })
        }
	}
	if(tempDictObjct){
		var array = tempDictObjct[key];
		array = array?array:[];
		for(var i=0; i<array.length; i++){
			if(array[i].code == code){
				if(color){
					if(color == 1){
						return "<span style='color:"+array[i].dictColor+"'>"+array[i].remarks+"</span>";
					}else if(color == 2){
						return "<span class='layui-badge' style='background-color:"+array[i].dictColor+"'>"+array[i].remarks+"</span>";
					}
				}else{
					return array[i].remarks;
				}
			}
		}
	}
	return code;
}

var tempTableColumn;
/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 表格筛选存储获取-是否显示
 * @param key 字段名称
 */
function setColumnHide(key) {
	// localStorage.removeItem("name"); // 移除
	if(!tempTableColumn){
        if(!columnObjectName){
            var href = window.location.href;
            var index = href .lastIndexOf("\/");
            columnObjectName = "human-resources-system_"+href .substring(index + 1, href.length);
        }
		tempTableColumn = localStorage.getItem(columnObjectName);
		tempTableColumn = tempTableColumn?JSON.parse(tempTableColumn):null;
	}
	if(tempTableColumn){
	    return tempTableColumn[key];
    }
    return false;
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 表格筛选触发事件-筛选存储
 * @param e 复选框对象
 * @returns
 */
var columnObjectName;
function table_tool(e) {
    if(!columnObjectName){
        var href = window.location.href;
        var index = href .lastIndexOf("\/");
        columnObjectName = "human-resources-system_"+href .substring(index + 1, href.length);
    }
    var field = $(e.elem).attr("name")
    var obj = localStorage.getItem(columnObjectName);
    obj = obj?JSON.parse(obj):{};
    if(e.elem.checked){
        obj[field] = false;
    }else{
        obj[field] = true;
    }
    localStorage.setItem(columnObjectName, JSON.stringify(obj));
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 提示
 * @param msg 提示内容
 * @returns
 */
function showTips(msg) {
    var s = '<span class="all-icon layui-layer-save-icon layui-layer-save-col-cancel">&#xe643;</span>';
    s += '<span class="layui-layer-save-tips">' + msg + '</span>';
    if (msg && (msg.indexOf("失败") != -1 || msg.indexOf("禁用") != -1 || msg.indexOf("关闭") != -1 || msg.indexOf("错误") != -1)) {
        s = '<span class="all-icon layui-layer-save-icon layui-layer-save-col-error">&#xe632;</span>';
        s += '<span class="layui-layer-save-tips">' + msg + '</span>';
    }else if (msg && (msg.indexOf("成功") != -1 || msg.indexOf("确定") != -1 || msg.indexOf("完成") != -1)) {
        s = '<span class="all-icon layui-layer-save-icon layui-layer-save-col-ok">&#xe614;</span>';
        s += '<span class="layui-layer-save-tips ">' + msg + '</span>';
    }
    layer.confirm(s, {
        title: false,
        time: 0,
        closeBtn: 0,
        shade: false,
        anim: 1,
        offset: '5%',
        btn: false,
        //zIndex: layer.zIndex,
        success: function (layero) {
        	var left = $(layero).offset().left;
        	$(layero).css({"min-width":"125px", 'left': (left+60)+'px', 'border':'1px solid #fff', 'box-shadow':'#0000001c 0px 1px 5px 0px'});
        	$(layero).find('.layui-layer-content').css({'padding':'5px', 'line-height':'normal'});
            // 鼠标放上
        	var tempTime;
            tempTime = setTimeout(function () {
                $(layero).fadeOut();
                tempTime = setTimeout(function () {
                    $(layero).remove();
                }, 2000)
            }, 3000)
        	$(layero).on({
                mouseover : function(){
                    clearTimeout(tempTime);
                } ,
                mouseout : function(){
                    tempTime = setTimeout(function () {
                        $(layero).fadeOut();
                        tempTime = setTimeout(function () {
                            $(layero).remove();
                        }, 2000)
                    }, 3000)
                }
            });
        }
    });
}


/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 打开自定义内容提示
 * @param msg 提示内容
 * @returns
 */
function showMsg(msg) {
    layer.open({
        type: 1,
        shade: 0.1,
        title: false,
        content: "<div style='padding: 20px'>" + msg + "</div>",
        success: function (layero) {
        	var obj = $(layero).find('.layui-layer-setwin');
        	obj.html('<div class="layui-layer-close layui-layer-close2 layui-layer-close-div"><i class="layui-icon">&#x1007;</i></div>');
        }
    });
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 打开加载中
 * @param msg 提示内容
 * @returns
 */
function showLoadMsg(msg) {
    var s = '<i class="all-icon layui-anim layui-anim-rotate layui-anim-loop" style="color: white;font-size: 30px;">&#xe8fc;</i>';
    var lay = layer.msg(s + "<span style='position: relative;top: -4px;left: 6px;'>" + msg + "...</span>", {
        shade: 0.1,
        time: 0,
    });
    return lay;
}
/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 打开加载中
 * @returns
 */
function showLoad() {
    var s = '<i class="all-icon layui-anim layui-anim-rotate layui-anim-loop" style="color: #5fb878;font-size: 30px;">&#xe6ac;</i>';
    var lay = layer.msg(s, {
        shade: ['gray', 0.1],
        time: 0,
        success: function (layero) {
        	$(layero).css({'min-width':'80px', 'background':'none'});
        	$(layero).find('.layui-layer-content').css({'padding':'10px'});
        }
    });
    return lay;
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 上面弹出弹框（一般用于查询）
 *
 * 打开iframe 宽、高传入对应像素例如：100px 或 100%
 * 表单ID、标题、宽度、高度、按钮['确认','取消']、时间（1000）、全屏、默认全屏、表单数据data
 * notStr 不重置值，格式：'#id,#id2,.id3'
 * @returns
 */
function openWindowSearch(formid, title, width, height, btn, time, max, full, myData, sha, shac, callbak) {
    if(title.indexOf('新增') != -1 || title.indexOf('添加') != -1){
    	title = "<i class='layui-icon layui-icon-add-circle' style='position: relative;right: 3px;top: 1px;'></i>" + title;
    }else if (title.indexOf('编辑') != -1 || title.indexOf('修改') != -1) {
    	title = "<i class='layui-icon layui-icon-edit' style='position: relative;right: 3px;top: 1px;'></i>" + title;
    }else if (title.indexOf('查看') != -1 || title.indexOf('详情') != -1) {
    	title = "<i class='layui-icon layui-icon-read' style='position: relative;right: 3px;top: 1px;'></i>" + title;
    }else if(title.indexOf('查询') != -1 || title.indexOf('搜索') != -1){
    	title = "<i class='layui-icon layui-icon-search' style='position: relative;right: 3px;top: 1px;'></i>" + title;
    }else if(title.indexOf('授权') != -1 || title.indexOf('权限') != -1){
    	title = "<i class='layui-icon layui-icon-auz' style='position: relative;right: 3px;top: 1px;'></i>" + title;
    }
    var w = $(document).width();
    var h = $(document).height();
    if(width.indexOf("px") != -1){
        var ww = width.replace("px", "");
        if(Number(ww) > w){
            width = "90%";
        }
    }
    if(height.indexOf("px") != -1){
        var hh = height.replace("px", "");
        if(Number(hh) > h){
            height = "90%";
        }
    }
    var index = layer.open({
        title: title,
        type: 1,
        offset: 't', // 参考：https://blog.csdn.net/hua_ban_yu/article/details/82773626
        anim: 5, // 参考：https://blog.csdn.net/qq_28137309/article/details/104674320
        maxmin: max ? max : false,
        skin: '',// 样式类名
        area: [width, height],
        btn: btn,
        shade: sha ? sha : false,
        shadeClose: shac ? shac : false,
        content: $("#" + formid),
        time: time,
        full: function (data) {
            $(data).find(".layui-layer-content").css('height', $(data).height() - 43)
        },
        resizing: function (data) {
            $(data).find(".layui-layer-content").css('height', $(data).height() - 43)
        },
        min: function (data) {
            $(data).find(".layui-layer-content").css('height', $(data).height() - 43)
        },
        restore: function (data) {
            $(data).find(".layui-layer-content").css('height', $(data).height() - 43)
        },
        cancel: function (index, layero) {// 关闭叉回调
            layer.close(index);
            return false;
        },
        end : function() {// 任何关闭窗口操作回调
			$("#"+formid).css("display", "none");
		},
        //zIndex: layer.zIndex,
        success: function (layero) {
        	// 关闭按钮
        	$(layero).find(".lay-close-btn").click(function(){
        		layer.close(index);
        	})
            // 重置按钮
        	$(layero).find(".lay-reset-btn").click(function(){
                $('#'+formid)[0].reset();
        	})
        	// 搜索时，下拉弹出层
        	if((title.indexOf('查询') != -1 || title.indexOf('搜索') != -1) && w > mobileMin){
            	$(layero).find('.layui-layer-content').addClass('layer-conten-out');
        	}
        	// 隐藏提交按钮
        	if (title.indexOf('查看') != -1 || title.indexOf('详') != -1) {
                $(layero).find('.lay-detail').removeClass("lay-detail-hiden").addClass("lay-detail-show");
                $(layero).find('.lay-submit-btn').css({'display':'none', 'pointer-events':'none'});// 隐藏按钮且让按钮失去点击事件，下面相反
                $(layero).find('.lay-submit-btn').addClass("layui-btn-disabled").attr("disabled", true);
        		$('#' + formid).find("input,textarea,select").prop('disabled', true).attr('disabled', true);
        	}else{
                $(layero).find('.lay-detail').removeClass("lay-detail-show").addClass("lay-detail-hiden");
        		$(layero).find('.lay-submit-btn').css({'display':'inline-block', 'pointer-events':'auto'});
        		$(layero).find('.lay-submit-btn').removeClass("layui-btn-disabled").attr("disabled", false);
        		$('#' + formid).find("input,textarea,select").prop('disabled', false).attr('disabled', false);
        	}
        	// 表单赋值
            //setFormData(formid, myData);
        	if(myData){
        		$('#'+formid)[0].reset();
            	form.val(formid, myData);
        	}
        	form.render();
            // 关闭图标更改
        	$(layero).find(".layui-layer-ico").css('background', 'none');
        	$(layero).find(".layui-layer-close").html('<i class="layui-icon layui-layer-close-icon layui-icon-close"></i>');
            // 回调函数
            if(callbak){
            	callbak(myData);
        	}
        }
    });
    if (full || w < mobileMin) {
        layer.full(index);
    }
    return index;
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 右下弹框（一般用于设置）
 * 
 * 打开iframe 宽、高传入对应像素例如：100px 或 100%
 * 表单ID、标题、宽度、高度、按钮['确认','取消']、时间（1000）、全屏、默认全屏、表单数据data
 * notStr 不重置值，格式：'#id,#id2,.id3'
 * @returns
 */
function openWindowRB(formid, title, width, height, btn, time, max, full, myData, sha, shac, callbak) {
	if(title.indexOf('新增') != -1 || title.indexOf('添加') != -1){
    	title = "<i class='layui-icon layui-icon-add-circle' style='position: relative;right: 3px;top: 1px;'></i>" + title;
    }else if (title.indexOf('编辑') != -1 || title.indexOf('修改') != -1) {
    	title = "<i class='layui-icon layui-icon-edit' style='position: relative;right: 3px;top: 1px;'></i>" + title;
    }else if (title.indexOf('查看') != -1 || title.indexOf('详情') != -1) {
    	title = "<i class='layui-icon layui-icon-read' style='position: relative;right: 3px;top: 1px;'></i>" + title;
    }else if(title.indexOf('查询') != -1 || title.indexOf('搜索') != -1){
    	title = "<i class='layui-icon layui-icon-search' style='position: relative;right: 3px;top: 1px;'></i>" + title;
    }else if(title.indexOf('授权') != -1 || title.indexOf('权限') != -1){
    	title = "<i class='layui-icon layui-icon-auz' style='position: relative;right: 3px;top: 1px;'></i>" + title;
    }
    var index = layer.open({
        title: title,
        type: 1,
        offset: 'rb',
        anim: 2,
        maxmin: max ? max : false,
        skin: '',// 样式类名
        area: [width, height],
        btn: btn,
        shade: sha ? sha : false,
        shadeClose: shac ? shac : false,
        content: $("#" + formid),
        time: time,
        full: function (data) {
            $(data).find(".layui-layer-content").css('height', $(data).height() - 43)
        },
        resizing: function (data) {
            $(data).find(".layui-layer-content").css('height', $(data).height() - 43)
        },
        min: function (data) {
            $(data).find(".layui-layer-content").css('height', $(data).height() - 43)
        },
        restore: function (data) {
            $(data).find(".layui-layer-content").css('height', $(data).height() - 43)
        },
        cancel: function (index, layero) {// 关闭叉回调
            layer.close(index);
            return false;
        },
        end : function() {// 任何关闭窗口操作回调
			$("#"+formid).css("display", "none");
		},
        success: function (layero) {
        	// 关闭按钮
        	$(layero).find(".lay-close-btn").click(function(){
        		layer.close(index);
        	})
            // 重置按钮
            $(layero).find(".lay-reset-btn").click(function(){
                $('#'+formid)[0].reset();
            })
        	// 隐藏提交按钮
        	if (title.indexOf('查看') != -1 || title.indexOf('详') != -1) {
                $(layero).find('.lay-detail').removeClass("lay-detail-hiden").addClass("lay-detail-show");
        		$(layero).find('.lay-submit-btn').css({'display':'none', 'pointer-events':'none'});// 隐藏按钮且让按钮失去点击事件，下面相反
        		$(layero).find('.lay-submit-btn').addClass("layui-btn-disabled").attr("disabled", true);
        		$('#' + formid).find("input,textarea,select").prop('disabled', true).attr('disabled', true);
        	}else{
                $(layero).find('.lay-detail').removeClass("lay-detail-show").addClass("lay-detail-hiden");
        		$(layero).find('.lay-submit-btn').css({'display':'inline-block', 'pointer-events':'auto'});
        		$(layero).find('.lay-submit-btn').removeClass("layui-btn-disabled").attr("disabled", false);
        		$('#' + formid).find("input,textarea,select").prop('disabled', false).attr('disabled', false);
        	}
        	// 表单赋值
            //setFormData(formid, myData);
        	$('#'+formid)[0].reset();
        	form.val(formid, myData);
        	form.render();
            // 关闭图标更改
        	$(layero).find(".layui-layer-ico").css('background', 'none');
            $(layero).find(".layui-layer-close").html('<i class="layui-icon layui-layer-close-icon layui-icon-close"></i>');
            // 回调函数
            if(callbak){
            	callbak(myData);
        	}
        }
    });
    var w = $(document).width();
    if (full || w < mobileMin) {
        layer.full(index);
    }
    return index;
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 默认弹框、居中弹框（一般用于增删改查）
 * 
 * 打开iframe 宽、高传入对应像素例如：100px 或 100%
 * 表单ID、标题、宽度、高度、按钮['确认','取消']、时间（1000）、全屏、默认全屏、表单数据data
 * notStr 不重置值，格式：'#id,#id2,.id3'
 * @returns
 */
function openWindow(formid, title, width, height, btn, time, max, full, myData, sha, shac, callbak) {
    if(title.indexOf('新增') != -1 || title.indexOf('添加') != -1){
    	title = "<i class='layui-icon layui-icon-add-circle' style='position: relative;right: 3px;top: 1px;'></i>" + title;
    }else if (title.indexOf('编辑') != -1 || title.indexOf('修改') != -1) {
    	title = "<i class='layui-icon layui-icon-edit' style='position: relative;right: 3px;top: 1px;'></i>" + title;
    }else if (title.indexOf('查看') != -1 || title.indexOf('详情') != -1) {
    	title = "<i class='layui-icon layui-icon-read' style='position: relative;right: 3px;top: 1px;'></i>" + title;
    }else if(title.indexOf('查询') != -1 || title.indexOf('搜索') != -1){
    	title = "<i class='layui-icon layui-icon-search' style='position: relative;right: 3px;top: 1px;'></i>" + title;
    }else if(title.indexOf('授权') != -1 || title.indexOf('权限') != -1){
    	title = "<i class='layui-icon layui-icon-auz' style='position: relative;right: 3px;top: 1px;'></i>" + title;
    }
    var w = $(document).width();
    var h = $(document).height();
    if(width.indexOf("px") != -1){
        var ww = width.replace("px", "");
        if(Number(ww) > w){
            width = "90%";
        }
    }
    if(height.indexOf("px") != -1){
        var hh = height.replace("px", "");
        if(Number(hh) > h){
            height = "90%";
        }
    }
    var index = layer.open({
        title: title,
        type: 1,
        maxmin: max ? max : false,
        skin: '',// 样式类名
        area: [width, height],
        btn: btn,
        shade: sha ? sha : false,
        shadeClose: shac ? shac : false,
        content: $("#" + formid),
        time: time,
        full: function (data) {
            $(data).find(".layui-layer-content").css('height', $(data).height() - 43)
        },
        resizing: function (data) {
            $(data).find(".layui-layer-content").css('height', $(data).height() - 43)
        },
        min: function (data) {
            $(data).find(".layui-layer-content").css('height', $(data).height() - 43)
        },
        restore: function (data) {
            $(data).find(".layui-layer-content").css('height', $(data).height() - 43)
        },
        cancel: function (index, layero) {// 关闭叉回调
            layer.close(index);
            return false;
        },
        end : function() {// 任何关闭窗口操作回调
			$("#"+formid).css("display", "none");
		},
        success: function (layero) {
        	// 关闭按钮
        	$(layero).find(".lay-close-btn").click(function(){
        		layer.close(index);
        	})
            // 重置按钮
            $(layero).find(".lay-reset-btn").click(function(){
                $('#'+formid)[0].reset();
            })
        	// 隐藏提交按钮
        	if (title.indexOf('查看') != -1 || title.indexOf('详') != -1) {
                $(layero).find('.lay-detail').removeClass("lay-detail-hiden").addClass("lay-detail-show");
        		$(layero).find('.lay-submit-btn').css({'display':'none', 'pointer-events':'none'});// 隐藏按钮且让按钮失去点击事件，下面相反
        		$(layero).find('.lay-submit-btn').addClass("layui-btn-disabled").attr("disabled", true);
        		$('#' + formid).find("input,textarea,select").prop('disabled', true).attr('disabled', true);
        	}else{
                $(layero).find('.lay-detail').removeClass("lay-detail-show").addClass("lay-detail-hiden");
        		$(layero).find('.lay-submit-btn').css({'display':'inline-block', 'pointer-events':'auto'});
        		$(layero).find('.lay-submit-btn').removeClass("layui-btn-disabled").attr("disabled", false);
        		$('#' + formid).find("input,textarea,select").prop('disabled', false).attr('disabled', false);
        	}
        	// 表单赋值
            //setFormData(formid, myData);
        	$('#'+formid)[0].reset();
        	form.val(formid, myData);
        	form.render();
        	
            // 关闭图标更改
        	$(layero).find(".layui-layer-ico").css('background', 'none');
            $(layero).find(".layui-layer-close").html('<i class="layui-icon layui-layer-close-icon layui-icon-close"></i>');
            // 表单必填*号（$("#" + formid).html() 或者 $("#" + formid).text()下使用）
//            $(".req").each(function(){
//            	var reqText = $(this).html();
//                $(this).html(reqText+"<span style='color:red;'>*</span>");
//            })
            // 回调函数
            if(callbak){
            	callbak(myData);
        	}
        }
    });
    if (full || w < mobileMin) {
        layer.full(index);
    }
    return index;
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 弹框访问跳转页面
 * 
 * @param title 标题
 * @param url 请求路径
 * @param width 宽度 (宽、高传入对应像素例如：100px 或 100%)
 * @param height 高度
 * @param max 是否打开全屏图标
 * @param full 是否全屏
 * @returns
 */
function openIframeWindow(title, url, width, height, max, full) {
    var w = $(document).width();
    var h = $(document).height();
    if(width.indexOf("px") != -1){
        var ww = width.replace("px", "");
        if(Number(ww) > w){
            width = "90%";
        }
    }
    if(height.indexOf("px") != -1){
        var hh = height.replace("px", "");
        if(Number(hh) > h){
            height = "90%";
        }
    }
    var index = layer.open({
        title: title,
        type: 2,
        shade: 0.2,
        maxmin: max ? max : false,
        area: [width, height],
        btn: false,
        content: url,
        full: function (data) {
            $(data).find(".layui-layer-content").css('height', $(data).height() - 43)
        },
        resizing: function (data) {
            $(data).find(".layui-layer-content").css('height', $(data).height() - 43)
        },
        min: function (data) {
            $(data).find(".layui-layer-content").css('height', $(data).height() - 43)
        },
        restore: function (data) {
            $(data).find(".layui-layer-content").css('height', $(data).height() - 43)
        },
        cancel: function (index, layero) {
            layer.close(index)
            return false;
        },
    });
    var w = $(document).width();
    if (full || w < mobileMin) {
        layer.full(index);
    }
    return index;
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 给表单赋值
 * 
 * @param formid 表单ID
 * @param myData 赋值参数
 * @param notStr 哪些选择器不需要赋值
 * @returns
 */
function setFormData(formid, myData) {
    $(':input', '#' + formid).not(':button, :submit, :reset,').val('').removeAttr('checked').removeAttr('selected');
    $('#' + formid + " textarea").val('');
    $('#'+formid)[0].reset();
    form.render();
    if (myData) {
        for (var key in myData) {
            if ($("#" + formid).find("[name='" + key + "']").is("select")) {
                $("#" + formid).find("[name='" + key + "']").find("option[value='" + myData[key] + "']").prop("selected", "selected")
                $("#" + formid).find("[name='" + key + "']").find("option[value='" + myData[key] + "']").attr("selected", "selected")
                form.render("select")
            } else {
                if ($("#" + formid).find("input[name='" + key + "']").attr("type") == "radio") {
                    $("#" + formid).find("input[title='" + myData[key] + "']").prop("checked", "checked")
                    $("#" + formid).find("input[title='" + myData[key] + "']").attr("checked", "checked")
                    form.render("radio")
                } else if ($("#" + formid).find("input[name='" + key + "']").attr("type") == "checkbox") {
                    $("#" + formid).find("input[name='" + key + "']").prop("checked", myData[key] ? (myData[key] > 0 ? true : false) : false)
                    $("#" + formid).find("input[name='" + key + "']").attr("checked", myData[key] ? (myData[key] > 0 ? true : false) : false)
                    form.render("checkbox")
                } else {
                    $("#" + formid).find("[name='" + key + "']").val(myData[key])
                }
            }
        }
    }
    form.render();
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 加载下来框数据
 *
 * 下拉框直接是用name做值,并且路径自动指定(支持多ID逗号分开)
 * @param url 访问的action路径
 * @param data 请求参数
 * @param selectId 渲染的selectid
 * @param oneState 是否第一个需要‘请选择’
 * @param id 渲染的 value值
 * @param name 渲染的 text名称
 * @return
 */
function loadDownSelector(url, data, selectId, oneState, id, name, call) {
    $.post(url, data, function (res) {
        if (res.success) {
            createOptions(res.data, selectId, oneState, id, name);
            if (call) {
                call(res);
            }
        }
    })
}
function createOptions(list, selectId, oneState, id, name) {
    var array = selectId.split(",");
    var s = "";
    if (list && list.length > 0) {
        if (list[0][name] != '请选择' && oneState) {
            s += "<option value=''>请选择</option>"
        }
        for (var i = 0; i < list.length; i++) {
            var obj = list[i];
            if (obj[name] != '请选择') {
                s += "<option hid='" + obj[id] + "' value='" + obj[id] + "'>" + obj[name] + "</option>"
            } else {
                s += "<option value=''>" + obj[name] + "</option>"
            }
        }
    }
    for (var i = 0; i < array.length; i++) {
        $("#" + array[i]).html(s);
    }
    form.render("select");
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 重载表格
 * 
 * @param tables 表格对象
 * @param tableId 表格ID
 * @param data 查询参数
 * @param notCurr 不从第一页开始，否则相反
 * @returns
 */
function reloadTable(tables, tableId, data, notCurr) {
	var obj = {};
	if(notCurr){
		if(data){
			obj.where = data;
		}
	}else{
		obj.page = {curr: 1};
		if(data){
			obj.where = data;
		}
	}
	tables.reload(tableId, obj);
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 根据表格ID获取当前表格选中的所有行ID
 * 
 * @param tableId 表格ID
 * @param id 字段名称
 * @returns
 */
function getTableCheckIds(tableId, id) {
    var checkStatus = table.checkStatus(tableId);
    var ids = "";
    for (var i = 0; i < checkStatus.data.length; i++) {
        if (ids == "") {
            ids = checkStatus.data[i]['' + id]
        } else {
            ids += "," + checkStatus.data[i]['' + id]
        }
    }
    return ids;
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 批量删除
 * 
 * @param tableObj 表格名称
 * @param tableId 表格ID
 * @param id 字段名称
 * @param url 请求路径
 * @param call 回调函数
 * @param data 请求参数
 * @param title 提示
 * @returns
 */
function deleteBatch(tableObj, tableId, id, url, call, data, title) {
    var checkStatus = table.checkStatus(tableId); //test即为基础参数id对应的值
    if (checkStatus.data.length > 0) {
        var ids = getTableCheckIds(tableId, id);
        if (!data) {
        	data = {};
        }
        data['ids'] = ids;
        var msg = title ? title : '确定删除已选中的信息么？';
    	var s = '<span class="all-icon layui-layer-save-icon layui-layer-save-col-cancel" style="font-size: 30px;">&#xe603;</span>';
    	s += '<span class="layui-layer-save-tips" style="font-size: 14px;color: #524f4f;">' + msg + '</span>';
        layer.confirm(s, {
            title: false,
            time: 0,
            closeBtn: 0,
            shade: 0.1,
            shadeClose: true,
            offset: '20%',
            success: function (layero) {
            }
        }, function (index) {
        	getAjax(url, data, 'post', function (res) {
                if (res.success) {
                    reloadTable(tableObj, tableId);
                }
                showTips(res.msg);
                if (call) {
                    call(res);
                }
            })
    	    layer.close(index);
        });
    } else {
        layer.msg("请至少选中一行删除")
    }
    return false;
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 删除某行
 * 
 * @param tableObj 表格名称
 * @param tableId 表格ID
 * @param data 请求参数
 * @param url 请求路径
 * @param call 回调函数
 * @param title 提示
 * @returns
 */
function deleteRow(tableObj, tableId, data, url, call, title) {
	var msg = title ? title : '真的删除行么？';
	var s = '<span class="all-icon layui-layer-save-icon layui-layer-save-col-cancel" style="font-size: 30px;">&#xe603;</span>';
	s += '<span class="layui-layer-save-tips" style="font-size: 14px;color: #524f4f;">' + msg + '</span>';
    layer.confirm(s, {
        title: false,
        time: 0,
        closeBtn: 0,
        shade: 0.1,
        offset: '20%',
        shadeClose: true,
        success: function (layero) {
        	$(layero).css({'border':'0px', 'box-shadow':'#adafaf 0px 0px 50px 0px'});
        }
    }, function (index) {
    	getAjax(url, data, 'DELETE', function (res) {
	        if (res.success) {
	            reloadTable(tableObj, tableId);
	        }
	        showTips(res.msg);
	        if (call) {
	            call(res);
	        }
	    })
	    layer.close(index);
    });
    return false;
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 保存
 * 
 * @param tableObj 表格名称
 * @param tableId 表格ID
 * @param data 请求参数
 * @param url 请求路径
 * @param call 回调函数
 * @returns
 */
function saveData(tableObj, tableId, data, url, formId, call, layIndex) {
	var text = sbumitLoading(formId+' .lay-submit-btn');
	getAjax(url, data, 'POST', function (res) {
        if (res.success) {
        	if(layIndex){
        		layer.close(layIndex);
        	}else{
        		layer.closeAll();
        	}
            reloadTable(tableObj, tableId);
        }
        showTips(res.msg);
        closeLoading(formId+' .lay-submit-btn', text)
        if (call) {
            call(res);
        }
	})
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * ajax接口
 * @param url 请求路径
 * @param data 请求参数
 * @param type 请求方式
 * @param callbak 成功回调
 * @param dataType 返回格式类型
 * @returns
 */
function getAjax(url, data, type, callbak, dataType, contentType){
	var ajaxObj = $.ajax({
		url: url, // 请求的URL
		//timeout: 1000*30, // 超时时间设置，单位毫秒
		type : type || 'get', // 请求方式，get或post
		data: data, // 请求所传参数，json格式
        contentType : contentType || 'application/x-www-form-urlencoded;charset=UTF-8',
		dataType: dataType || 'json',// 返回的数据格式
		success: function(res){ // 请求成功的回调函数
		    if(res.code == 401){
                notLogin();
            }else {
                if(callbak){
                    callbak(res);
                }
            }
		},
		complete: function(XMLHttpRequest, status){ // 请求完成后最终执行参数
			if(status == 'timeout'){// 超时, status 还有 success, error等值的情况
				ajaxObj.abort(); // 关闭ajax请求
				if(callbak){
					callbak({success: false, msg: "操作失败，接口请求超时！"});
				}
			}else if(status == 'error'){// 超时, status 还有 success, error等值的情况
				ajaxObj.abort(); // 关闭ajax请求
				if(callbak){
					callbak({success: false, msg: "操作失败，接口请求错误！"});
				}
			}else if(status == 'parsererror'){
                ajaxObj.abort(); // 关闭ajax请求
                callbak({success: false, msg: "操作失败，接口请求错误！"});
                notLogin();
            }
		}
	});
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 未登录提示
 */
function notLogin() {
    var s = '<span class="layui-icon layui-layer-save-icon layui-layer-save-col-error" style="font-size: 30px;">&#x1007;</span>';
    s += '<span class="layui-layer-save-tips" style="font-size: 14px;color: #524f4f;">登录已过期,是否刷新页面?</span>';
    layer.confirm(s, {
        title: false,
        time: 0,
        closeBtn: 0,
        shade: 0.1,
        offset: '20%',
        shadeClose: true,
        success: function (layero) {
            $(layero).css({'border': '0px', 'box-shadow': '#adafaf 0px 0px 50px 0px'});
        }
    }, function (index) {
        window.location.reload();
        layer.close(index);
    });
}


/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 提交按钮加载中
 * @param tab
 * @returns
 */
function sbumitLoading(tab){
	var tempText = $(tab).text();
	$(tab).html(tempText+'<i class="layui-icon layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop layui-ext-icon-selected-icon"></i>');
	$(tab).css('pointer-events', 'none');
	$(tab).addClass("layui-btn-disabled").attr("disabled", true);
	return tempText;
}
/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 关闭提交按钮的加载中
 * @param tab
 * @param text
 * @returns
 */
function closeLoading(tab, text){
	$(tab).html(text);
	$(tab).css('pointer-events', 'auto');
	$(tab).removeClass("layui-btn-disabled").attr("disabled", false);
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 获取当前年
 * @returns
 */
function getYear(){
    var time = new Date();
    return time.getFullYear();
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 系统时间
 * @param t 是否只是获取日期 yyyy-MM-dd，默认yyyy-MM-dd HH:mm:ss
 * @param index 年份是否需要累加
 * @returns
 */
function getSysDate(t,index){
	if(!index){
		index = 0;
	}
	var time = new Date();
	var month = ((time.getMonth()+1)+"").length < 2?"0"+(time.getMonth()+1):(time.getMonth()+1);
	var dates = (time.getDate()+"").length < 2?"0"+time.getDate():time.getDate();
	var minute = (time.getMinutes()+"").length < 2?"0"+time.getMinutes():time.getMinutes();
	var hours = (time.getHours()+"").length < 2?"0"+time.getHours():time.getHours();
	var minute = (time.getMinutes()+"").length < 2?"0"+time.getMinutes():time.getMinutes();
	var second = (time.getSeconds()+"").length < 2?"0"+time.getSeconds():time.getSeconds();
	var s = (time.getFullYear()+index)+"-"+month+"-"+dates+" "+hours+":"+minute+":"+second;
	if(t){
		s = (time.getFullYear()+index)+"-"+month+"-"+dates;
	}
	return s;
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * 替换所有
 *
 * @param str 字符串
 * @param FindText 需替换
 * @param RepText 替换为
 * @returns
 */
function replaceAll(str, FindText, RepText){
    if(!str){
        return "";
    }
    var regExp = new RegExp(FindText, "g");
    return str.replace(regExp, RepText);
}

/**
 * ------------------------------------------------------------------------------------------------------------------------------------------
 * IP获取
 * 
 * @param onNewIP
 * @returns
 */
function getUserIP(onNewIP) {
    var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
    var pc = new myPeerConnection({
            iceServers: []
        }),
        noop = function () {
        },
        localIPs = {},
        ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
        key;

    function iterateIP(ip) {
        if (!localIPs[ip]) onNewIP(ip);
        localIPs[ip] = true;
    }

    pc.createDataChannel("");
    pc.createOffer().then(function (sdp) {
        sdp.sdp.split('\n').forEach(function (line) {
            if (line.indexOf('candidate') < 0) return;
            line.match(ipRegex).forEach(iterateIP);
        });
        pc.setLocalDescription(sdp, noop, noop);
    }).catch(function (reason) {
    });
    pc.onicecandidate = function (ice) {
        if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
        ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
    };
}





